package com.easy.service.impl;

import com.easy.annotation.LogMethod;
import com.easy.bean.Appointment;
import com.easy.mapper.AppointmentMapper;
import com.easy.mapper.ScheduleMapper;
import com.easy.service.AppointmentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
@EnableTransactionManagement
@Service
public class AppointmentServiceImpl implements AppointmentService {

    @Resource
    private AppointmentMapper appointmentMapper;

    @Resource
    private ScheduleMapper scheduleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reserve(Integer userId, Integer doctorId, Integer scheduleId) {
        // 确认该时段可预约（is_deleted=0）
        var schedule = scheduleMapper.one(scheduleId);
        if (schedule == null || schedule.getIs_deleted() != null && schedule.getIs_deleted() == 1) {
            throw new IllegalStateException("该时间段不可预约或不存在");
        }

        // 占位：把该时间段置为已占用
        schedule.setIs_deleted(1);
        scheduleMapper.edit(schedule);

        // 写入预约记录
        Appointment a = new Appointment();
        a.setUser_id(userId);
        a.setDoctor_id(doctorId);
        a.setSchedule_id(scheduleId);
        a.setStatus("RESERVED");
        a.setIs_deleted(0);
        appointmentMapper.insert(a);
    }

    @Override
    public List<Map<String, Object>> myList(Integer userId) {
        return appointmentMapper.myList(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(Integer id, Integer userId) {
        // 校验归属
        int ok = appointmentMapper.countByIdAndUser(id, userId);
        if (ok == 0) {
            throw new IllegalStateException("该预约不存在或已取消");
        }
        // 查到预约，取出 schedule_id
        var appt = appointmentMapper.one(id);
        if (appt == null) throw new IllegalStateException("该预约不存在");

        // 1) 标记预约为删除 & 状态 CANCELED
        appointmentMapper.logicalDelete(id, userId);

        // 2) 释放该时段：schedule.is_deleted = 0
        var schedule = scheduleMapper.one(appt.getSchedule_id());
        if (schedule != null) {
            schedule.setIs_deleted(0);
            scheduleMapper.edit(schedule);
        }
    }
}
